
import axios from 'axios';
import qs from 'qs';
import 'xgplayer';
import HlsPlayer from 'xgplayer-hls';

import {
    API,
    ALLOWED_TYPES,
    UPLOAD_INFO,
    CHUNK_SIZE
} from './config';

;((doc) => {

    const oProgress = doc.querySelector('#uploadProgress'),
          oUploader = doc.querySelector('#videoUploader'),
          oInfo = doc.querySelector('#uploadInfo'),
          oStartBtn = doc.querySelector('#startBtn'),
          oPauseBtn = doc.querySelector('#pauseBtn');

    let paused = false,
        uploadedSize = 0,
        uploadResult = null,
        uploadedFileName = "";

    const init = () => {
        switchUploader(true);
        bindEvent();
    }

    function bindEvent(){
        oStartBtn.addEventListener('click', uploadVideo, false);
        // 点击的时候 传入 true 让其暂停
        oPauseBtn.addEventListener('click', switchUploader.bind(null, true), false);
    }

    async function uploadVideo () {
        switchUploader(false);
        
        const { files: [ file ] } = oUploader;

        if(!file){
            oInfo.innerText = UPLOAD_INFO['NO_FILE'];
            return;
        }

        if(!ALLOWED_TYPES[file.type]){
            oInfo.innerText = UPLOAD_INFO['INVALID_TYPE'];
            return;
        }

        const  { name, size, type } = file;

        oProgress.max = size;
        uploadedSize = Number(localStorage.getItem(name) || 0); // 获取缓存
        oInfo.innerText = UPLOAD_INFO['UPLOADING'];

        while (uploadedSize < size && !paused){
            const chunk = file.slice(uploadedSize, uploadedSize + CHUNK_SIZE),
                  chunkName = new Date().getTime() + '_' + name.replace(`.${ALLOWED_TYPES[type]}`, ''),
                  formData = createFormData({ name, type, size, chunkName, chunk});

            try{
                uploadResult = await axios.post(API.UPLOAD_VIDEO, formData);
                console.log(uploadResult);
            }catch(e){
                oInfo.innerText = `${UPLOAD_INFO['FAILED']}(${ e.message })`;
                return;
            }

            uploadedSize += chunk.size;
            oProgress.value = uploadedSize;
            localStorage.setItem(name, uploadedSize);
        }

        mergeVideo(name, type);
    }

    async function mergeVideo(name, type){
        if(!paused){
            oUploader.value = null;
            uploadedFileName = uploadResult.data.fileName;
            oInfo.innerText = UPLOAD_INFO['TRANSCODING'];

            const res = await axios.post(API.MERGE_VIDEO, qs.stringify({
                fileName: uploadedFileName,
                type
            }));

            localStorage.removeItem(name);

            if(res.data.code === 1006){
                oInfo.innerText = `${UPLOAD_INFO['FAILED']}(${res.data.msg})`;
                return;
            }

            oInfo.innerText = UPLOAD_INFO['SUCCESS'];
            switchUploader(true);

            new HlsPlayer({
                id: 'videoContainer',
                url: res.data.videoSrc
            });
        }
    }

    function createFormData ({
        name, type, size, chunkName, chunk
    }){
        const fd = new FormData();
        fd.append('name', name);
        fd.append('type', type);
        fd.append('size', size);
        fd.append('chunkName', chunkName);
        fd.append('chunk', chunk);

        return fd;
    }

    function switchUploader(bool){ // true 表示当前是暂停或完成状态，显示 上传按钮
        paused = bool;

        oStartBtn.style.display = paused ? 'block' : 'none';
        oPauseBtn.style.display = paused ? 'none' : 'block';
    }


    init();
})(document);
